﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.EditPages
{
    public partial class EditCustomer : BasePage
    {
        Customers cust;
        int custID;
        string mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (Request.QueryString[KEY] == null)
            {
                CloseDlg(0);
                return;
            }

            if (Request.QueryString[MODE] == null)
            {
                CloseDlg(0);
                return;
            }

            mode = Request.QueryString[MODE];

            if (Request.QueryString[ID] == null && (mode == EDIT_MODE || mode == VIEW_MODE))
            {
                CloseDlg(0);
                return;
            }

            //if (!IsPostBack)
            //    editCustomer.InitData();

            cust = (Customers)Session[Request.QueryString[KEY]];
            string oldFilter = cust.Filter;

            custID = Request.QueryString[ID] != null ? int.Parse(Request.QueryString[ID]) : 0;
            if (mode != ADD_MODE)
                cust.Filter = Customers.ColumnNames.ID + "=" + custID.ToString();
            else
                btnSave.Enabled = false;

            if (!IsPostBack && cust.RowCount > 0 && mode != ADD_MODE)
                LoadInfo();

            cust.Filter = oldFilter;
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            Save();
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true);
        }

        private bool Save()
        {
            string oldFilter = cust.Filter;
            try
            {
                if (mode == ADD_MODE)
                {
                    if (editCustomer.Email != "" && Customers.GetCustomerByEmail(editCustomer.Email).RowCount > 0)
                        throw new ApplicationException("This email has been used. Please choose another one.");
                    cust.AddNew();
                    cust.BranchID = Branches.CurrentBranchID;
                    cust.Deleted = false;
                    cust.TotalAmount = 0;
                    cust.PaidAmount = 0;
                    cust.Password = Utilities.CreateMD5Hash(Utilities.GetConfigAppSetting("DefaultPassword"));
                }
                else
                {
                    cust.Filter = Customers.ColumnNames.ID + "=" + custID;
                }

                if (editCustomer.CustomerType > 0)//when saving foreign key, remember to check condition or we may get confliction
                    cust.CustomerType = editCustomer.CustomerType;
                cust.LastModifiedByUser = SessionUser.ID;
                cust.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                cust.CustomerName = editCustomer.CustomerName;
                cust.Address = editCustomer.Address;
                cust.Phone = editCustomer.Phone;
                cust.Mobile = editCustomer.Mobile;
                cust.Email = editCustomer.Email;
                cust.Company = editCustomer.Company;
                cust.Fax = editCustomer.Fax;
                cust.s_CreditLine = editCustomer.s_CreditLine;
                
                cust.Save();
                cust.Filter = oldFilter;
                ((Popup)Master).ShowMessage("Saved");
                return true;
            }
            catch (Exception ex)
            {
                cust.RejectChanges();
                cust.Filter = oldFilter;

                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("editCustomer.aspx.cs", "Save", ex.StackTrace);
                return false;
            }
        }

        private void LoadInfo()
        {
            try
            {
                if (!cust.IsColumnNull(Customers.ColumnNames.CustomerType))
                    editCustomer.CustomerType = cust.CustomerType;
                if (!cust.IsColumnNull(Customers.ColumnNames.CustomerName))
                    editCustomer.CustomerName = cust.CustomerName;
                if (!cust.IsColumnNull(Customers.ColumnNames.Address))
                    editCustomer.Address = cust.Address;
                if (!cust.IsColumnNull(Customers.ColumnNames.Company))
                    editCustomer.Company = cust.Company;
                if (!cust.IsColumnNull(Customers.ColumnNames.Phone))
                    editCustomer.Phone = cust.Phone;
                if (!cust.IsColumnNull(Customers.ColumnNames.Mobile))
                    editCustomer.Mobile = cust.Mobile;
                if (!cust.IsColumnNull(Customers.ColumnNames.Fax))
                    editCustomer.Fax = cust.Fax;
                if (!cust.IsColumnNull(Customers.ColumnNames.Email))
                    editCustomer.Email = cust.Email;
                editCustomer.s_CreditLine = cust.s_CreditLine;
            }
            catch (Exception ex)
            {
                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("editCustomer.aspx.cs", "LoadInfo", ex.StackTrace);
            }
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            if (Save())
                CloseDlg(1);
        }
    }
}
